<template>
  <div class="add">
    <!-- 页头 -->
    <el-page-header @back="goBack" :content="titleText + '商品'">
    </el-page-header>
    <el-card>
      <!-- 警告 -->
      <el-alert :title="titleText + '商品信息'" type="info" show-icon center>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="300"
        :active="activeIndex - 0"
        finish-status="success"
        :align-center="true"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form ref="addForm" :model="addForm" :rules="addFormRules">
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTabLeave"
        >
          <el-tab-pane
            label="基本信息"
            name="0"
            style="height: 80vh; overflow: auto"
          >
            <!-- 基本信息的表单内容 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                }"
                clearable
                :disabled="routeId ? true : false"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabs"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals" @change="handleSortChange">
                <el-checkbox
                  :label="vals"
                  v-for="(vals, j) in item.attr_vals"
                  :key="j"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-alert
              title="抱歉，该功能尚未完善"
              type="info"
              :closable="false"
              v-show="manyTabs.length === 0"
            ></el-alert>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabs"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals" ></el-input>
            </el-form-item>
            <el-alert
              title="抱歉，该功能尚未完善"
              type="info"
              :closable="false"
              v-show="manyTabs.length === 0"
            ></el-alert>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :file-list="imgList"
              :action="`${$store.state.BASE_URL_3}upload`"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headerObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
            <el-dialog
              title="图片预览"
              :visible.sync="imgDialogVisible"
              width="50%"
              top="10vh"
            >
              <el-image :src="imgSrc"></el-image>
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="changeGoods">{{titleText + '商品'}}</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getHomeData } from "network/home.js";

export default {
  name: "Add",
  data() {
    return {
      // 被选中的标签页
      activeIndex: "0",
      // 表单数据相关
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [
          {
            attr_id: 15,
            attr_value: "ddd",
          },
          {
            attr_id: 15,
            attr_value: "eee",
          },
        ],
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
      // 所有分类列表
      cateList: [],
      // 在编辑时，商品的图片
      imgList: [],
      // 在上传文件时，添加头部信息
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      imgDialogVisible: false,
      // 点击图片查看放大图时的，url存储
      imgSrc: "",
      // 当处于编辑状态时，存储id
      routeId: "",
      // 商品参数列表的存储
      manyTabData: [],
      // 商品属性的列表(仅编辑商品时有用)
      detailList: [],
      manyTabs: [],
      onlyTabs: []
    };
  },
  created() {
    this.getCateList();
    let id = this.$route.query.id;
    this.routeId = this.$route.query.id;
    id ? this.getGoodsData(id) : null;
  },
  methods: {
    getGoodsData(id) {
      getHomeData({
        url: `goods/${id}`,
      }).then((res) => {
        // console.log(res);
        if (res.meta.status !== 200)
          return this.$message({
            type: "error",
            message: res.meta.msg,
          });
        this.addForm = res.data;
        this.addForm.goods_cat = this.addForm.goods_cat.split(",");
        res.data.attrs.forEach(
          (item) => (item.attr_vals = item.attr_vals.split(/,| /))
        );
        this.manyTabData = res.data.attrs;
        res.data.pics.map((item) =>
          this.imgList.push({ name: res.data.goods_name, url: item.pics_big_url })
        );
        this.detailList = res.data.goods_introduce?.match(/(?<=src=")\S*(?=")/g) ?? []
        // this.detailList = /^(src=")(\S*)"$/g.exec(res.data.goods_introduce)
      });
    },
    goBack() {
      this.$router.back();
    },
    getCateList() {
      getHomeData({
        url: "categories",
        params: {
          type: 3,
        },
      }).then((res) => {
        if (res.meta.status !== 200)
          return this.$message({
            type: "error",
            message: res.meta.msg,
          });
        this.cateList = res.data;
      });
    },
    beforeTabLeave(new_name, old_name) {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message({
          type: "error",
          message: "请选择第三级的商品分类",
        });
        return false;
      }
      
      // console.log(new_name);
      // console.log(this.activeIndex);
      if (new_name == "1" || new_name == "2") {
        let sel = new_name == "1" ? 'many' : 'only'
        getHomeData({
          url: `categories/${this.cateId}/attributes`,
          params: {
            sel
          },
        })
        .then(val => {
          if(val.meta.status != 200) return this.$message.error('获取动态参数列表失败')
          // console.log(val.data);
          sel === 'many' && val.data.forEach(v => v.attr_vals = v.attr_vals.split(',') || [])
          if(sel === 'many') this.manyTabs = val.data
          else this.onlyTabs = val.data
        })
        
      }
    },
    // 图片预览
    handlePreview(file) {
      this.imgSrc = file.url;
      this.imgDialogVisible = true;
    },
    // 图片删除
    handleRemove(file) {
      // console.log(file);
      // console.log(this.addForm.pics);
      // const filePath = file.response.data.tmp_path || file.url;
      const filePath = file.url;
      const index = this.addForm.pics.findIndex((x) => x.pics_big === filePath);
      this.addForm.pics.splice(index, 1);
    },
    // 图片上传成功
    handleSuccess(res) {
      const picInfo = { pic: res.data.tmp_path };
      this.addForm.pics.push(picInfo);
      console.log(this.addForm.pics);
    },
    changeGoods() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) {
          return this.$message({
            type: "error",
            message: "请填写所有的必填项",
          });
        }
        let newForm = JSON.parse(JSON.stringify(this.addForm));
        // console.log(this.addForm);
        console.log(newForm);
        newForm.goods_cat = newForm.goods_cat.join(",");

        let res;
        try {
          if(!this.routeId) {
            res = await getHomeData(
              {
                url: "goods",
                data: newForm,
              },
              "post"
            )
          } else {
            res = await getHomeData(
              {
                url: `goods/${this.routeId}`,
                data: newForm,
              },
              "put"
            )
          }
          console.log(res);
          if ((res.meta.status !== 200 && this.routeId) || (res.meta.status !== 201 && !this.routeId)) throw res
          this.$message({
            type: "success",
            message: `${this.titleText}成功`,
          });
          this.$router.back();
        } catch (error) {
          console.log(error);
          this.$message.error(`${this.titleText}失败`)
        }
      });
    },
    handleSortChange(val) {
      console.log(val);
    }
  },
  computed: {
    titleText() {
      return this.routeId ? "编辑" : "添加";
    },
    cateId() {
      if(this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
};
</script>

<style scoped>
.el-page-header,
.el-alert {
  margin-bottom: 15px;
}

.add /deep/ .el-step__title {
  font-size: 14px;
}

.el-step {
  margin-bottom: 15px;
}

.el-tab-pane /deep/.ql-container {
  height: 260px;
  overflow: auto;
}

.quill-editor {
  margin-bottom: 15px;
}

.el-form-item /deep/ .el-checkbox {
  margin: 0 5px;
}

.el-tab-pane {
  max-height: 450px;
  overflow: auto;
}
.el-card {
  height: 80vh;
}
</style>